package com.tanhua.admin.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.admin.mapper.FreezeMapper;
import com.tanhua.commons.utils.DateConversionUtils;
import com.tanhua.dubbo.api.MovementApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.model.db.Freeze;
import com.tanhua.model.db.Movement;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.db.Video;
import com.tanhua.model.vo.MovementsVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VideoVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @auther : 白月尘
 * @date : 13:51  2021/10/28
 */
@Service
public class ManageService {
    @DubboReference
    private UserInfoApi userInfoApi;
    @DubboReference
    private VideoApi videoApi;
    @DubboReference
    private MovementApi movementApi;
    @Autowired
    private FreezeMapper freezeMapper;
    //查询用户
    public PageResult findUsers(Integer page, Integer pageSize) {
        IPage<UserInfo> iPage = userInfoApi.findAll(page, pageSize);
        List<UserInfo> userInfos = new ArrayList<>();
        for (UserInfo userInfo : iPage.getRecords()) {
            UserInfo newUserInfo = this.getUserStatus(userInfo.getId(), userInfo);
            userInfos.add(newUserInfo);
        }
        return new PageResult(page, pageSize, iPage.getTotal(), userInfos/*iPage.getRecords()*/);
    }

    public UserInfo findByUserID(long userID) {
        UserInfo userInfo = userInfoApi.findById(userID);
        UserInfo newUserInfo = getUserStatus(userID, userInfo);
        return newUserInfo;
    }

    //查询用户的冻结状态
    private UserInfo getUserStatus(Long id, UserInfo userInfo) {
        Freeze freeze = freezeMapper.selectByUid(id);
        if (freeze != null) {

            Date currentDate = DateConversionUtils.parseStrToDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                    .format(new Date()), "yyyy-MM-dd HH:mm:ss", new Date());
            Date unfreezeTime = freeze.getUnfreezeTime();
            Long timeDifference = freezeMapper.selectFreezeTimeDifference(currentDate,unfreezeTime );
            if (timeDifference <= 0) {
                //已到解封时间
                userInfo.setUserStatus("1");
                freeze.setIsFreezing(1);//1解冻，2冻结
                freeze.setReasonsForThawing("到期自动解冻~");
                freezeMapper.updateById(freeze);
            } else {
                //当前用户被冻结
                userInfo.setUserStatus("2");
            }
        }
        return userInfo;
    }
    //冻结操作
    public String freezeUser(Long userId, Integer freezingTime, Integer freezingRange, String reasonsForFreezing, String frozenRemarks) {
        Freeze freeze = freezeMapper.selectByUid(userId);
        if (freeze == null) {
            freeze = new Freeze();
            freeze.setUserId(userId);
            freeze.setFreezingTime(freezingTime);
            if (freezingTime == 1) {
                freeze.setUnfreezeTime(DateUtil.offsetDay(new Date(), 3));
            } else if (freezingTime == 2) {
                freeze.setUnfreezeTime(DateUtil.offsetDay(new Date(), 7));
            } else {
                freeze.setUnfreezeTime(DateUtil.parse("2099-01-01 00:00:00"));
            }
            freeze.setFreezingRange(freezingRange);
            freeze.setReasonsForFreezing(reasonsForFreezing);
            freeze.setIsFreezing(2);//1为正常，2为冻结
            freeze.setFrozenRemarks(frozenRemarks);
            freezeMapper.insert(freeze);
        }else {
            freeze.setUserId(userId);
            freeze.setFreezingTime(freezingTime);
            if (freezingTime == 1) {
                freeze.setUnfreezeTime(DateUtil.offsetDay(new Date(), 3));
            } else if (freezingTime == 2) {
                freeze.setUnfreezeTime(DateUtil.offsetDay(new Date(), 7));
            } else {
                freeze.setUnfreezeTime(DateUtil.parse("2099-01-01 00:00:00"));
            }
            freeze.setFreezingRange(freezingRange);
            freeze.setReasonsForFreezing(reasonsForFreezing);
            freeze.setIsFreezing(2);//1为正常，2为冻结
            freeze.setFrozenRemarks(frozenRemarks);
            freezeMapper.updateById(freeze);
        }
        return "1";
    }
    //解冻操作
    public String unfreezeUser(Long userId, String reasonsForThawing) {
        Freeze freeze = freezeMapper.selectByUid(userId);
        if (freeze == null) {
            return "";
        }
        //设置解冻原因，解冻时间，解冻状态
        freeze.setReasonsForThawing(reasonsForThawing);
        freeze.setUnfreezeTime(new Date());
        freeze.setIsFreezing(1);//1解冻，2冻结
        freezeMapper.updateById(freeze);
        return "1";
    }
    //查询视频列表
    public PageResult findVideos(Integer page, Integer pageSize, long uid) {
        PageResult pageResult = videoApi.findVideoById(page, pageSize, uid);
        List<Video> items = (List<Video>) pageResult.getItems();
        if (CollUtil.isEmpty(items)) {
            return pageResult;
        }
        List<Long> userId = CollUtil.getFieldValues(items, "userId", long.class);
        Map<Long, UserInfo> map = userInfoApi.findAll(userId);
        List<VideoVo> vos = new ArrayList<>();
        for (Video video : items) {
            UserInfo userInfo = map.get(video.getUserId());
            if (userInfo != null) {
                VideoVo init = VideoVo.init(userInfo, video);
                vos.add(init);
            }
        }
        pageResult.setItems(vos);
        return pageResult;
    }

    //查询动态列表
    public PageResult findMovements(Integer page, Integer pageSize, Long uid, Integer state) {
        PageResult pageResult = movementApi.findMovements(page, pageSize, uid, state);
        if (pageResult == null || pageResult.getItems() == null) {
            return new PageResult();
        }
        List<Movement> items = (List<Movement>) pageResult.getItems();
        List<Long> userId = CollUtil.getFieldValues(items, "userId", long.class);
        Map<Long, UserInfo> map = userInfoApi.findAll(userId);
        List<MovementsVo> vos = new ArrayList<>();
        for (Movement movement : items) {
            UserInfo userInfo = map.get(movement.getUserId());
            if (userInfo != null) {
                MovementsVo init = MovementsVo.init(userInfo, movement);
                vos.add(init);
            }
        }
        pageResult.setItems(vos);
        return pageResult;
    }

    //根据id查询动态
    public Movement findMovementById(String id) {
        //System.out.println(id);
        Movement movement = movementApi.findById(id);
        return movement;
    }

   /*public String pass(String[] split) {
        return null;
    }*/

    /*
    动态通过
  */
    public String pass(String[] message) {
        String  tongguo =  movementApi.updateCommentState(message);
        return tongguo;
    }

    //动态拒绝
    public String reject(String[] message) {
        String  jujue =  movementApi.updateReState(message);
        return jujue;
    }
}
